package com.app.orderconsumer;

import com.app.service.OrdersServer;
import com.common.entity.Orders;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 王鑫
 * @create 2020 -11 -24 14:34
 * 添加订单的消费者
 */
@Component
public class OrderConsumer {

    @Autowired
    OrdersServer ordersServer;
    @Autowired
    RedisTemplate redisTemplate;

    @RabbitListener(queues = "queuedelay")
    public void addOrder(Orders orders, Message message, Channel channel) throws IOException {
        //调用添加订单到数据库
        System.out.println("------------开始处理订单----------------" + new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss a E").format(new Date()));
        System.out.println("接收到的订单:" + orders);
        ListOperations listOperations = redisTemplate.opsForList();
        //添加到数据库中
        int result = ordersServer.addorders(orders);
        //添加到缓存中
        listOperations.leftPush(orders.getOrdersId(), orders);
        if (result != 0) {
            System.out.println("------------执行订单成功----------------" + new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss a E").format(new Date()));
            //添加成功进数据库和Redis处理成功ACK
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            //处理失败NACK
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

}
